package vip.xls8z.es.sample.controller;

import com.alibaba.fastjson.JSON;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregator;
import org.elasticsearch.search.aggregations.metrics.sum.ParsedSum;
import org.elasticsearch.search.aggregations.metrics.sum.SumAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.tophits.ParsedTopHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import vip.xls8z.es.sample.dto.OrderBookDTO;

/**
 * @author tangzhijie
 * @date 2021/7/21
 */

@Slf4j
@RestController
@RequestMapping("/es")
public class ESController {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @GetMapping("/search/{index}")
    public List<OrderBookDTO> search(@PathVariable String index) throws IOException {
        List<OrderBookDTO> orderBookDTOList = new ArrayList<>();
        // 构建查询条件
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.filter(QueryBuilders.termQuery("isDeleted", false));

        queryBuilder.filter(QueryBuilders.wildcardQuery("name", "*苹果*"));

        // 构建返回字段
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.fetchSource(new String[]{"uid", "name", "money", "createdDate"}, null);
        sourceBuilder.query(queryBuilder);

        // 聚合数据
        /*
         * terms = group by
         * AggregationBuilders.terms("data").field("uid").size(0);
         *  - terms("data") 自定义名字
         *  - size(0) 0 拿所有数据统计，默认10条
         */
        TermsAggregationBuilder uidAggregationBuilder = AggregationBuilders.terms("data").field("uid").size(0);

        /*
         *  AggregationBuilders.sum("totalMoney").field("money")
         *  - sum("totalMoney") 自定义求和之后的字段名称，等价于 sum(money) as totalMoney
         */
        SumAggregationBuilder sumAggregationBuilder = AggregationBuilders.sum("totalMoney").field("money");

        // 按照 uid 分组之后再统计和
        uidAggregationBuilder.subAggregation(sumAggregationBuilder);
        sourceBuilder.aggregation(uidAggregationBuilder);

        // 排序
        FieldSortBuilder money = SortBuilders.fieldSort("money").order(SortOrder.DESC);
        sourceBuilder.sort(money);

        // 高亮搜索

        // 构建搜索请求
        SearchRequest searchRequest = new SearchRequest(index);
        searchRequest.source(sourceBuilder);
        sourceBuilder.from(0);
        sourceBuilder.size(1);

        log.debug("Search Builder: {}", sourceBuilder.toString());

        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] searchHits = response.getHits().getHits();
        //获取总记录数
        long totalElements = response.getHits().getTotalHits();
        log.info("{}: Search total elements: {}", Thread.currentThread().getName(), totalElements);

        for (SearchHit searchHit : searchHits) {
            OrderBookDTO orderBookDTO = JSON.parseObject(searchHit.getSourceAsString(), OrderBookDTO.class);
            orderBookDTOList.add(orderBookDTO);
        }

        // 获取聚合数据
        Aggregations aggregations = response.getAggregations();
        ParsedStringTerms parsedStringTerms = aggregations.get("data");
        for (Terms.Bucket bucket : parsedStringTerms.getBuckets()) {
            Aggregations tmpAgg = bucket.getAggregations();
            Object key = bucket.getKey();
            Map<String, Aggregation> asMap = tmpAgg.getAsMap();
            ParsedSum totalMoney = (ParsedSum) asMap.get("totalMoney");
            double value = totalMoney.getValue();
            log.info("key: {}, value: {}",key.toString(), value);
        }

        return orderBookDTOList;
    }

}
